package com.zj.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
/**
 * 微信接口封装
 * @author 张剑
 *
 */
public class WxUtil {
	private final static String APPID = "wxca355c26f045d4c3";
	private final static String SECERT = "876ae3d2ab23f345bb9c5cc34a24cdb5";
	private static final long MAX_TIME = 3600 * 1000;
	//小程序获取用户openid
		@SuppressWarnings("rawtypes")
		public static String getSmallOpenid(String code) throws IOException {
			  // 拼接api要求的httpsurl链接
		String urlString = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid="
			      + "wx598dab44fe0b616f" + "&secret=" + "037537299bbaa10a9c9f767d5a96f3ed"+"&js_code="+code;
			  // 创建一个url
			  URL reqURL = new URL(urlString);
			  // 拿取链接
			  HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL
			      .openConnection();
			  // 取得该连接的输入流，以读取响应内容
			  InputStreamReader isr = new InputStreamReader(
			      httpsConn.getInputStream());
			  // 读取服务器的响应内容并显示
			  char[] chars = new char[1024];
			  String reslut = "";
			  int len;
			  while ((len = isr.read(chars)) != -1) {
			    reslut += new String(chars, 0, len);
			  }
			  isr.close();
			  Map map=JSON.parseObject(reslut);			 
			  return (String) map.get("openid");
			}
	
	
	public static Access_token getAccess_token() throws IOException {
		  // 拼接api要求的httpsurl链接
		  String urlString = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
		      + APPID + "&secret=" + SECERT;
		  // 创建一个url
		  URL reqURL = new URL(urlString);
		  // 拿取链接
		  HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL
		      .openConnection();
		  // 取得该连接的输入流，以读取响应内容
		  InputStreamReader isr = new InputStreamReader(
		      httpsConn.getInputStream());
		  // 读取服务器的响应内容并显示
		  char[] chars = new char[1024];
		  String reslut = "";
		  int len;
		  while ((len = isr.read(chars)) != -1) {
		    reslut += new String(chars, 0, len);
		  }
		  isr.close();
		 
		  // 注意：Access_token access_token是一个自己创建的javabean
		  Access_token access_token = new Access_token();
		  
		  access_token=JSON.parseObject(reslut, Access_token.class);
		  access_token.setExpires_in(System.currentTimeMillis());
		  return access_token;
		}
	//获取用户openid
	public static String getOpenid(String code) throws IOException {
		  // 拼接api要求的httpsurl链接
		  String urlString = "https://api.weixin.qq.com/sns/oauth2/access_token?grant_type=authorization_code&appid="
		      + APPID + "&secret=" + SECERT+"&code="+code;
		  // 创建一个url
		  URL reqURL = new URL(urlString);
		  // 拿取链接
		  HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL
		      .openConnection();
		  // 取得该连接的输入流，以读取响应内容
		  InputStreamReader isr = new InputStreamReader(
		      httpsConn.getInputStream());
		  // 读取服务器的响应内容并显示
		  char[] chars = new char[1024];
		  String reslut = "";
		  int len;
		  while ((len = isr.read(chars)) != -1) {
		    reslut += new String(chars, 0, len);
		  }
		  isr.close();
		  Map map=JSON.parseObject(reslut);
		 
		  return (String) map.get("openid");
		}
	public static String getSavedAccess_token() throws IOException {
	        
		
		 String path="E:/weixin/temp_access_token.temp";
	     String token="";
	     File file = new File(path);  
	        if (!file.getParentFile().exists()) {  
	          
	        	file.getParentFile().mkdir();	        	
	            
	        } 
	      if (!file.exists()) {      	
	            file.createNewFile();  
	        } 
		 
		  if (file.length() == 0) {
		   
		    FileOutputStream fos = new FileOutputStream(file, false);// 不允许追加
		    Access_token access_token=getAccess_token();
		    String json =JSON.toJSONString(access_token) ;		    
		    fos.write((json).getBytes());
		    fos.close();
		    token= access_token.getAccess_token();
		  } else {
		    // 读取文件内容
		    FileInputStream fis = new FileInputStream(file);
		    byte[] b = new byte[2048];
		    int len = fis.read(b);
		    String mJsonAccess_token = new String(b, 0, len);// 读取到的文件内容
		    Access_token access_token = JSON.parseObject(mJsonAccess_token, Access_token.class);
		    if (access_token.getExpires_in() != null) {
		      long saveTime = access_token.getExpires_in();
		      long nowTime = System.currentTimeMillis();
		      long remianTime = nowTime - saveTime;
		      if (remianTime < MAX_TIME) {
		    	  token= access_token.getAccess_token();
		      } else {
		    	try {
		    		Access_token access_tokencxhq=getAccess_token();
		    		  
			        String json =JSON.toJSONString(access_tokencxhq) ;	
			        FileOutputStream fos = new FileOutputStream(file, false);// 不允许追加
			        fos.write((json).getBytes());
			        fos.close();
			        token= access_tokencxhq.getAccess_token();
				} catch (Exception e) {
					e.printStackTrace();
				}
		    	
		      }
		 
		    }
		  }
		return token;
		 
		 
		}
	
	//消息模板
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map getbd(String name,String openid){

		Map map = new HashMap();
		map.put("template_id", "VG_ZKv9n1KzDqOYgNiE3QVOKCnk2SMtAEUWq3dflgsU");
		map.put("touser", openid);
		Map data=new HashMap();
		Map first=new HashMap();
		first.put("value", "用户绑定成功！");
		first.put("color", "#173177");
		
		Map keyword1=new HashMap();
		keyword1.put("value", name);
		keyword1.put("color", "#173177");
		
		Map keyword2=new HashMap();
		keyword2.put("value", "您已成功绑定实验室信息管理系统");
		keyword2.put("color", "#173177");
		

		Map remark=new HashMap();
		remark.put("value", "欢迎使用实验室信息管理系统，我们竭诚为您服务！");
		remark.put("color", "#173177");
		
		data.put("first", first);
		data.put("keyword1", keyword1);
		data.put("keyword2", keyword2);
		data.put("remark", remark);
		
		
		
		map.put("data", data);
		return map;
	}

		@SuppressWarnings({ "rawtypes", "unchecked" })
		public static Map getsybd(String name,String openid,String syrq,String synr,String title){

			Map map = new HashMap();
			map.put("template_id", "GRQ8Qaf5LsPC75pbjgC79h-HTc0jhklx6sZwQWzqiqg");
			map.put("touser", openid);
			Map small = new HashMap<>();
			small.put("appid", "wx598dab44fe0b616f");
			small.put("pagepath", "pages/index/index");
			map.put("miniprogram", small);
			
		
			Map data=new HashMap();
			
			Map first=new HashMap();
			first.put("value", title);
			first.put("color", "#173177");
			
			Map keyword1=new HashMap();
			keyword1.put("value", name);
			keyword1.put("color", "#173177");
			
			Map keyword2=new HashMap();
			keyword2.put("value",syrq);
			keyword2.put("color", "#173177");
			
			Map keyword3=new HashMap();
			keyword3.put("value",synr);
			keyword3.put("color", "#173177");
			

			Map remark=new HashMap();
			remark.put("value", "欢迎使用实验室信息管理系统，我们竭诚为您服务！(点击跳转)");
			remark.put("color", "#173177");
			
			data.put("first", first);
			data.put("keyword1", keyword1);
			data.put("keyword2", keyword2);
			data.put("keyword3", keyword3);
			data.put("remark", remark);
			
			
			
			map.put("data", data);
			return map;
		}
	
	//shiyantixing
	@SuppressWarnings("rawtypes")
	public static Map fssy(String openid,String token,String syrq,String synr,String name,String title){
		String url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
		
		Map map =getsybd(name, openid, syrq, synr,title);
		String json = JSON.toJSONString(map);
		String ret=sendPost(url,json);
		Map mapret = JSON.parseObject(ret);
		return mapret;
	}
	
	
	//发送消息 
	public static Map fsxx(String openid,String token,String name){
		String url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
		
		Map map =getbd(name,openid);
		String json = JSON.toJSONString(map);
		String ret=sendPost(url,json);
		System.out.println(ret);
		Map mapret = JSON.parseObject(ret);
		return mapret;
	}
	 public static String sendPost(String url, String param) 
	 {
	            HttpPost httpPost = new HttpPost(url);
		        CloseableHttpClient client = HttpClients.createDefault();
		        String respContent = null;
		        

		        StringEntity entity = new StringEntity(param,"utf-8");//解决中文乱码问题    
		        entity.setContentEncoding("UTF-8");    
		        entity.setContentType("application/json");    
		        httpPost.setEntity(entity);
		        System.out.println();     
		        try {
		        	   HttpResponse resp = client.execute(httpPost);
				        if(resp.getStatusLine().getStatusCode() == 200) {
				            HttpEntity he = resp.getEntity();
				            respContent = EntityUtils.toString(he,"UTF-8");
				        }
				        
				    
				} catch (Exception e) {
					e.printStackTrace();
					
				}
		        return respContent;
		     
}
		

}
